/**
 * Created with JetBrains PhpStorm.
 * User: ishowshao
 * Date: 13-4-27
 */
var OnlineUsers = require('./OnlineUsers');
var User = require('./User');

//mongo db
var MongoDb = require("mongodb");

////////////////////////////////////////////////
//db -- user, collection -- user
var dbClient = new MongoDb.Db('plane', new MongoDb.Server('127.0.0.1', MongoDb.Connection.DEFAULT_PORT), {w: 1});
dbClient.open(function (err, db) {
    if (err) {
        console.log(err);
    } else {
        db.createCollection('user', function (err, c) {
        });
    }
});
var onlineUsers = new OnlineUsers();
/**
 * @type {Chita}
 */
var Bp = require('./Chita');
Bp.createServer();
Bp.autoStatic('/Users/ishowshao/htdocs/battle-plane');

Bp.route('/login', function () {
    var that = this;
    this.sessionStart();
    var output = {
        success: false,
        message: ''
    };
    var username = '';
    var password = '';
    if (typeof this.POST['username'] !== 'undefined') {
        username = String(this.POST['username']).trim();
    }
    if (typeof this.POST['password'] !== 'undefined') {
        password = this.POST['password'];
    }
    if (username) {
        dbClient.collection('user').findOne({username: username}, function (err, user) {
            if (!err) {
                console.log('login action', user);
                if (user && user.password === password) {
                    //login success
                    that.sessionSet('username', username);
                    that.sessionSet('id', user._id);
                    if (!onlineUsers.getUserById(username)) {
                        onlineUsers.addUser(new User({
                            id: user._id,
                            name: username
                        }));
                    }
                    output.success = true;
                } else {
                    output.message = '用户名或密码错误';
                }
            } else {
            }
            that.end(JSON.stringify(output));
        });
    } else {
        this.end(JSON.stringify(output));
    }
});

/**
 * 用户登出
 */
Bp.route('/logout', function () {
    this.sessionStart();

    var output = {
        success: true
    };

    var id = this.sessionGet('id');
    if (id) {
        onlineUsers.removeUser(onlineUsers.getUserById(id));
        this.sessionClear();
    }
    this.end(JSON.stringify(output));
});

/**
 * 新用户注册
 */
Bp.route('/register', function () {
    var that = this;
    var username = this.POST['username'];
    var password = this.POST['password'];
    var output = {
        success: false
    };
    if (username && password && username.length > 3 && password.length > 5) {
        dbClient.collection('user').insert({username: username, password: password}, function () {
            output.success = true;
            that.end(JSON.stringify(output));
        });
    } else {
        this.end(JSON.stringify(output));
    }
});

/**
 * 检查用户是否已经登录
 */
Bp.route('/is-login', function () {
    this.sessionStart();
    var output = {
        success: false,
        username: ''
    };
    var username = this.sessionGet('username');
    if (username) {
        output.success = true;
        output.username = username;
    }
    this.end(JSON.stringify(output));
});

/**
 * 获得在线列表
 */
Bp.route('/online-users', function () {
    var output = {
        success: true,
        data: onlineUsers.toArray()
    };
    this.end(JSON.stringify(output));
});

Bp.route('/message', function () {
    var that = this;
    //协议对象
    var message = {
        type: 'timeout',
        code: 0,
        data: {}
    };

    this.sessionStart();
    var username = this.sessionGet('username');
    var user = onlineUsers.getUserById(this.sessionGet('id'));
    if (!user) {
        this.end(JSON.stringify(message));
        return;
    }
    user.alive(); //报告自己活着


    var timer = setTimeout(function () {
        console.log('timeout');
        onlineUsers.removeListener('user-added', onUserOnline);
        onlineUsers.removeListener('user-removed', onUserOffline);
        that.end(JSON.stringify(message));
    }, 10 * 1000);

    var onUserOnline = function (u) {
        message.type = 'user';
        message.code = 1; //用户上线
        message.data = {
            id: u.getId(),
            name: u.getName()
        };
        that.end(JSON.stringify(message));

        //执行清理
        clearTimeout(timer);
        onlineUsers.removeListener('user-added', onUserOnline);
    };

    var onUserOffline = function (u) {
        message.type = 'user';
        message.code = 2; //用户离线
        message.data = {
            id: u.getId(),
            name: u.getName()
        };
        that.end(JSON.stringify(message));

        clearTimeout(timer);
        onlineUsers.removeListener('user-removed', onUserOffline);
    };

    onlineUsers.on('user-added', onUserOnline);
    onlineUsers.on('user-removed', onUserOffline);

});
